package com.jinzhi.jzweb.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.ChapterDO;
import com.jinzhi.jzweb.domain.ChapterLearnsDO;
import com.jinzhi.jzweb.domain.CourseLearnsDO;
import com.jinzhi.jzweb.domain.CoursesDO;
import com.jinzhi.jzweb.pojo.TrainingAgencyPageVo;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.DaysUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * 培训机构查看学员情况，只针对培训机构和讲师，其他角色暂不考虑
 * </pre>
 * <small> 2020-05-19 10:50:00 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/trainingAgencyPage")
public class TrainingAgencyPageController extends BaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private CourseLearnsService courseLearnsService;
    @Autowired
    private ChapterLearnsService chapterLearnsService;
    @Autowired
    private LearnRecordService learnRecordService;
    @Autowired
    private CoursesService coursesService;
    @Autowired
    private ChapterService chapterService;

    @GetMapping()
    @RequiresPermissions("jzweb:trainingAgencyPage:trainingAgencyPage")
    String TrainingPapers(){
        return "jzweb/trainingAgencyPage/trainingAgencyPage";
    }

    /**
     * 学习进度
     * @param pageNumber
     * @param pageSize
     * @param coursesName
     * @param userName
     * @param sex
     * @return
     */
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:trainingAgencyPage:trainingAgencyPage")
    public Result<Page<TrainingAgencyPageVo>> list(String pageNumber, String pageSize,String coursesName,String userName,String sex){
        // 新建分页
        Page<TrainingAgencyPageVo> page = new Page<TrainingAgencyPageVo>(Integer.parseInt(pageNumber), Integer.parseInt(pageSize));

        Map map = new HashMap();
        if (StringUtils.isNotBlank(coursesName)){
            map.put("coursesName",coursesName);
        }
        if (StringUtils.isNotBlank(userName)){
            map.put("userName",userName);
        }
        if (StringUtils.isNotBlank(sex)){
            map.put("sex",sex);
        }

        //查询角色
        String roleNames = getRoleNames();
        //讲师
        Map mapsa = new HashMap();
        mapsa.put("orgId",this.getUser().getOrgId());
        if(roleNames.contains("讲师") && !roleNames.contains("培训机构")){
            mapsa.put("userId",this.getUserId());
        }
        List<Long> cIds = coursesService.selCoursesIdList(mapsa);
        if(cIds != null && cIds.size() > 0){
            map.put("couIds",cIds);
            page = orderService.selTrainingAgency(Integer.parseInt(pageNumber), Integer.parseInt(pageSize),map);
            List list = new ArrayList();
            for (int i = 0; i < page.getRecords().size(); i++) {
                TrainingAgencyPageVo obj = (TrainingAgencyPageVo) page.getRecords().get(i);

                long allSize = 0;//总章节数
                List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", obj.getCoursesId());
                if (chapterDOS != null && chapterDOS.size() > 0) {
                    allSize = chapterDOS.size();
                }

                CourseLearnsDO courseLearnsDO = courseLearnsService.findOneByKv("courses_id", obj.getCoursesId(), "user_id", obj.getUserId());
                if (courseLearnsDO != null) {
                    long reSize = courseLearnsDO.getCompletionNumber();//完成章节数
                    if (courseLearnsDO.getState() == 0) {
                        obj.setLearnProgress("100%");
                    } else {
                        CoursesDO coursesDO = coursesService.selectById(obj.getCoursesId());
                        if (coursesDO.getAdoptFactor().equals("所有章节通过")) {
                            if (allSize != 0) {
                                if (reSize*100 / allSize >= 100) {
                                    obj.setLearnProgress("100%");
                                } else {
                                    obj.setLearnProgress((reSize*100 / allSize) + "%");
                                }
                            } else {
                                obj.setLearnProgress("0%");
                            }
                        } else if (coursesDO.getAdoptFactor().equals("所有章节通过以及测试达到合格")) {
                            if (allSize != 0) {
                                if(reSize != 0){
                                    if ((reSize / allSize)*100 >= 100) {
                                        obj.setLearnProgress("90%");
                                    } else {
                                        obj.setLearnProgress(((reSize*100 / allSize)*0.9) + "%");
                                    }
                                }else{
                                    obj.setLearnProgress("0%");
                                }
                            } else {
                                obj.setLearnProgress("0%");
                            }
                        } else {
                            //课程通过条件为：测试通过；那么这里的情况是课程没有通过，那么无论是有没有测试，都是返回百分之0
                            obj.setLearnProgress("0%");
                        }
                    }
                }else{
                    obj.setLearnProgress("*");
                }

                list.add(obj);
            }
            page.setRecords(list);
        }

        return Result.ok(page);
    }


    //查看学员清单
    @GetMapping("/studyDetails")
    @RequiresPermissions("jzweb:trainingAgencyPage:trainingAgencyPage")
    String add(Model model,String coursesId,String userId) {
        Map map = new HashMap();
        map.put("coursesId",Long.parseLong(coursesId));
        map.put("userId",Long.parseLong(userId));
        CourseLearnsDO courseLearnsDO = courseLearnsService.selCours(map);
        model.addAttribute("coursesId",coursesId);//课程id
        model.addAttribute("userId",userId);//学员id
        model.addAttribute("coursesName",courseLearnsDO.getCoursesName());//课程名
        model.addAttribute("userName",courseLearnsDO.getUserName());//学员名
        model.addAttribute("totalDuration",courseLearnsDO.getTotalDuration());//总时长
        model.addAttribute("practiceScores",courseLearnsDO.getPracticeScores());//练习成绩
        model.addAttribute("testScores",courseLearnsDO.getTestScores());//考试成绩
        model.addAttribute("state",courseLearnsDO.getState());//通过状态

        List<Map> noMaps = new ArrayList<>();
        List<Map> yesMaps = new ArrayList<>();
        List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", Long.parseLong(coursesId));
        if (chapterDOS != null && chapterDOS.size() > 0) {
            for(ChapterDO chapterDO : chapterDOS){
                Map map1 = new HashMap();
                map1.put("chapterName",chapterDO.getName());//章节名
                ChapterLearnsDO chapterLearnsDO = chapterLearnsService
                        .findOneByKv("courses_id", Long.parseLong(coursesId),"chapter_id",chapterDO.getId(),"user_id",Long.parseLong(userId));
                if (chapterLearnsDO != null) {
                    map1.put("chapterDuration",chapterLearnsDO.getTotalDuration());//章节学习时长
                    if(chapterLearnsDO.getState().equals(0)){
                        yesMaps.add(map1);
                    }else{
                        noMaps.add(map1);
                    }
                }else{
                    map1.put("chapterDuration",0);//章节学习时长
                    noMaps.add(map1);
                }
            }
        }
        model.addAttribute("yesMaps",yesMaps);//完成章节列表（章节列表包括章节名和章节学习时长）
        model.addAttribute("noMaps",noMaps);//未完成章节列表（章节列表包括章节名和章节学习时长）
        return "jzweb/trainingAgencyPage/studyDetails";
    }


    @ResponseBody
    @GetMapping("/learnRecords")
    @Log("学员学习情况页-学习情况信息")
    @ApiOperation(value = "学员学习情况页-学习情况信息", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> learnRecords(String userId,String type) {
        Map map = new HashMap();
        //查询角色
        String roleNames = getRoleNames();
        //讲师
        Map mapsa = new HashMap();
        mapsa.put("orgId",this.getUser().getOrgId());
        if(roleNames.contains("讲师") && !roleNames.contains("培训机构")){
            mapsa.put("userId",this.getUserId());
        }
        List<Long> cIds = coursesService.selCoursesIdList(mapsa);
        Map map1 = new HashMap();
        map1.put("userId",Long.parseLong(userId));
        map1.put("cIds",cIds);
        //近7天
        if(type.equals("0")){
            List<String> horizontalAxis = DaysUtil.testBefore(7);
            map.put("horizontalAxis",horizontalAxis);

            map1.put("days",7);
            List<Map> mapList = learnRecordService.selLearnInfrom(map1);

            List<String> verticalAxis = new ArrayList<>();
            for(String dayys : horizontalAxis){
                if(mapList != null && mapList.size() > 0){
                    boolean bbc = true;
                    for(Map map11 : mapList){
                        if(map11.get("date").equals(dayys)){
                            verticalAxis.add(map11.get("num").toString());
                            bbc = false;
                        }
                    }

                    if(bbc){
                        verticalAxis.add("0");
                    }
                }else{
                    verticalAxis.add("0");
                }
            }
            map.put("verticalAxis",verticalAxis);
        }else{
            List<String> horizontalAxis = DaysUtil.testBefore(30);
            map.put("horizontalAxis",horizontalAxis);

            map1.put("days",30);
            List<Map> mapList = learnRecordService.selLearnInfrom(map1);

            List<String> verticalAxis = new ArrayList<>();
            for(String dayys : horizontalAxis){
                if(mapList != null && mapList.size() > 0){
                    boolean bbc = true;
                    for(Map map11 : mapList){
                        if(map11.get("date").equals(dayys)){
                            verticalAxis.add(map11.get("num").toString());
                            bbc = false;
                        }
                    }

                    if(bbc){
                        verticalAxis.add("0");
                    }
                }else{
                    verticalAxis.add("0");
                }
            }
            map.put("verticalAxis",verticalAxis);
        }

        return ApiResult.success(map);
    }

}
